package com.lazily.collection_;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @Author:  GZQ
 * @date:  2025/4/15 20:51
 * @description: Collection 接口遍历元素方式 1 --- 使用 Iterator(迭代器)
 * @version: 1.0
 */

public class CollectionIterator {
	// 程序入口
	@SuppressWarnings({"all"})
	public static void main(String[] args) {
		Collection col = new ArrayList();

		col.add(new Book("三国演义", "罗贯中", 30.03));
		col.add(new Book("西游记", "吴承恩", 33.60));
		col.add(new Book("天龙八部", "金庸", 50.65));

		// System.out.println("col: " + col);

		// 遍历集合 使用 Iterator
		// 1. 先得到 col 对应的 迭代器
		Iterator iterator = col.iterator();
		// 2. 使用while循环遍历
		while (iterator.hasNext()) { // 判断是否还有数据
			// 返回下一个元素, 类型是Object
			Object obj = iterator.next();
			System.out.println("obj=" + obj);
		}

		// while 循环快捷键, 快速生成 while ==> itit
		// 显示所有的快捷键的的快捷键 ctrl + j
		// while (iterator.hasNext()) {
		// 	Object obj = iterator.next();
		// 	System.out.println("obj=" + obj);
		// }

		// 3. 当退出while 循环后, 这时iterator迭代器, 指向最后的元素
		// iterator.next(); // NoSuchElementException
		// 4. 如果希望再次变量, 需要重置我们的迭代器
		iterator = col.iterator();
		System.out.println("====第二次遍历=====");
		while (iterator.hasNext()) {
			Object obj = iterator.next();
			System.out.println("object=" + obj);
		}


	}
}

class Book {
	private String name;
	private String author;
	private double price;

	public Book(String name, String author, double price) {
		this.name = name;
		this.author = author;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	@Override
	public String toString() {
		return "Book{" +
				"name='" + name + '\'' +
				", author='" + author + '\'' +
				", price='" + price + '\'' +
				'}';
	}
}